package com.example.base.controller;

import com.example.base.util.Response;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/sys")
public class SysController {

    @PostMapping("/imageUpload")
    public Response imageUpload(@RequestPart(value = "file", required = false) MultipartFile file){
        Response response = new Response();
        if (file == null) {
            response.setError("请选择要上传的图片");
            return response;
        }
        if (file.getSize() > 1024 * 1024 * 10) {
            response.setError("文件大小不能大于10M");
            return response;
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            response.setError("请选择jpg,jpeg,gif,png格式的图片");
            return response;
        }
        String savePath = "K:/";
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        //通过UUID生成唯一文件名
        String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
        try {
            //将文件保存指定目录
            file.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            e.printStackTrace();
            response.setError("保存文件异常");
            return response;
        }
        //返回文件名称
//        response.setData(request);
        response.setMsg(filename);
        return response;
    }
}

